package com.dhms.uikit.media

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.fragment.app.FragmentManager
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.dhms.uikit.R
import com.dhms.uikit.databinding.ActivityMediaBinding
import kotlinx.coroutines.Job
import java.io.File

class MediaActivity : AppCompatActivity() {

    private lateinit var _binding: ActivityMediaBinding
    val binding get() = _binding

    private var navController: NavController? = null

    private var preToastCoroutine: Job? = null

    var currentMedia: MediaItem? = null

    lateinit var viewId: String

    lateinit var outputDirectory: File

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewId = intent.extras?.getString(VIEW_ID_KEY) ?: ""

        outputDirectory = getOutputDirectory(
            this,
            viewId
        )

        _binding = ActivityMediaBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_media_fragment) as NavHostFragment
        navController = navHostFragment.navController

        window?.apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                val windowInsetsController = decorView.windowInsetsController
                windowInsetsController?.systemBarsBehavior =
                    WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
                windowInsetsController?.hide(WindowInsets.Type.statusBars())
                setDecorFitsSystemWindows(false)
            } else {
                decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                        )
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            window?.attributes?.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }
    }

    override fun onDestroy() {
        super.onDestroy()


        navController = null
    }

    @SuppressLint("RestrictedApi")
    override fun onBackPressed() {
        if (navController?.currentDestination?.id == R.id.cameraFragment) {
            val intent = Intent(BROADCAST_CREATE_ACTION + viewId)
            sendBroadcast(intent)
            finishActivity()
            return
        }
        super.onBackPressed()
    }

    /**
     * Sets the displaying media item.
     */
    fun setCurrentMediaItem(mediaItem: MediaItem?) {
        currentMedia = mediaItem
    }

    /**
     * Finish the activity with a custom animation.
     */
    fun finishActivity() {
        ActivityCompat.finishAfterTransition(this)
    }

    companion object {
        const val TAG = "MediaActivity"

        const val FILENAME_FORMAT = "yyyy-MM-dd_HH-mm-ss"
        const val PHOTO_EXTENSION = ".jpg"
        const val VIDEO_EXTENSION = ".mp4"
        const val AUDIO_EXTENSION = ".aac"

        const val BROADCAST_CREATE_ACTION = "com.dhms.camera.broadcast.create_action-"
        const val BROADCAST_DELETE_ACTION = "com.dhms.camera.broadcast.delete_action-"
        const val VIEW_ID_KEY = "VIEW_ID"

        const val BROADCAST_FILE_PATH_KEY = "FILE_PATH"
        const val BROADCAST_FILE_TYPE_KEY = "FILE_TYPE"
        const val BROADCAST_FILE_THUMBNAIL_KEY = "FILE_THUMBNAIL"

        const val INTENT_TYPE_KEY = "INTENT_TYPE"
        const val INTENT_VIEW_INDEX_KEY = "INTENT_VIEW_INDEX"
        const val INTENT_FILE_LIST_KEY = "INTENT_FILE_LIST"
        const val INTENT_IS_PREVIEW_KEY = "INTENT_IS_PREVIEW"

        val SUPPORT_MEDIA_FORMAT_MAP: Map<MediaType, List<String>> = mapOf(
            MediaType.PHOTO to listOf("jpeg", "jpg", "png", "bmp"),
            MediaType.VIDEO to listOf("mp4", "avi", "3gp"),
            MediaType.AUDIO to listOf("m4a", "mp3", "wav", "aac"),
        )

        enum class IntentType {
            CAPTURE, MANAGE
        }

        fun getOutputDirectory(context: Context, id: String): File {
            val appContext = context.applicationContext
            val mediaDir = context.getExternalFilesDir(id)
            return if (mediaDir != null && mediaDir.exists())
                mediaDir else appContext.filesDir
        }

        /**
         * Start the activity with a custom animation.
         */
        fun startActivity(
            context: Context,
            activity: Activity,
            id: String,
            intentType: IntentType = IntentType.CAPTURE,
            fileList: Array<String> = arrayOf(),
            viewIndex: Int = 0,
            isMediasPreview: Boolean = false
        ) {
            val intent = Intent(
                context.applicationContext,
                MediaActivity::class.java
            )
            intent.putExtra(VIEW_ID_KEY, id)
            intent.putExtra(INTENT_TYPE_KEY, intentType)
            intent.putExtra(INTENT_FILE_LIST_KEY, fileList)
            intent.putExtra(INTENT_VIEW_INDEX_KEY, viewIndex)
            intent.putExtra(INTENT_IS_PREVIEW_KEY, isMediasPreview)
            val optionsCompat =
                ActivityOptionsCompat.makeSceneTransitionAnimation(activity)
            ActivityCompat.startActivity(
                context,
                intent, optionsCompat.toBundle()
            )
        }
    }
}